<script setup lang="ts">
import type { TabPaneName } from 'element-plus'
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

interface TabInfo {
  path: string
  fullpath: string
  name: string
  title?: string
  meta?: any
  active?: boolean
  id?: string
}

const tabs = ref<TabInfo[]>([
  {
    path: '/',
    fullpath: '/',
    name: 'img2a4',
    title: '转PDF',
    meta: { title: '转PDF', closable: false },
  },
])
const activeTab = ref('/')

watch(
  () => route.fullPath,
  (newPath) => {
    const foundTab = tabs.value.find(tab => tab.fullpath === newPath)
    if (foundTab) {
      activeTab.value = foundTab.fullpath
    }
    else {
      tabs.value.push({
        path: route.path,
        fullpath: route.fullPath,
        name: route.name as string,
        meta: route.meta,
        title:
          typeof route.query.title === 'string'
            ? route.query.title
            : (route.meta?.title as string),
        id: `${JSON.stringify(route.fullPath)}-${JSON.stringify(route.params)}-${JSON.stringify(route.query)}`,
      })
      activeTab.value = route.fullPath
    }
  },
  { immediate: true },
)

watch(
  () => activeTab.value,
  (newPath) => {
    router.push(newPath)
  },
)

function handleTabsEdit(targetName: TabPaneName | undefined, action: 'remove' | 'add') {
  if (action === 'remove') {
    let activeName = activeTab.value
    if (activeName === targetName) {
      tabs.value.forEach((tab, index) => {
        if (tab.fullpath === targetName) {
          const nextTab = tabs.value[index + 1] || tabs.value[index - 1]
          if (nextTab) {
            activeName = nextTab.fullpath
          }
        }
      })
    }
    activeTab.value = activeName
    tabs.value = tabs.value.filter(tab => tab.fullpath !== targetName)
  }
}

// 更新选项卡状态
watch(() => route.path, (newPath) => {
  tabs.value.forEach((tab) => {
    tab.active = tab.path === newPath
  })
}, { immediate: true })
</script>

<template>
  <div class="border-b border-gray-300 bg-white" style="margin-bottom: 1px;">
    <div class="flex pl-4 -mb-px space-x-2">
      <el-tabs v-model="activeTab" class="tabs" @edit="handleTabsEdit">
        <el-tab-pane
          v-for="item in tabs"
          :key="item.fullpath"
          :label="item.title"
          :name="item.fullpath"
          :closable="item.fullpath === '/' ? false : true"
        />
      </el-tabs>
    </div>
  </div>
</template>

<style lang="css">
.tabs .el-tabs__header {
  margin: 0 0 0 0 !important;
}
</style>
